package com.mdlaser.service.impl;

import com.mdlaser.dto.OrderDetail;
import com.mdlaser.entity.WishLanguage;
import com.mdlaser.entity.WishType;
import com.mdlaser.service.IOrderConsumer;
import com.mdlaser.service.IOrdersWishesService;
import com.mdlaser.service.IWishLanguageService;
import com.mdlaser.service.IWishTypeService;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.FileHandler;


@Component
public class OrderConsumerImpl implements IOrderConsumer {

    private final static Logger log = LoggerFactory.getLogger("orderConsumer");

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    @Autowired
    IOrdersWishesService ordersWishesService;


    @Value("${laserControlServer:null}")
    String laserControlServer;

    public Map<String, ScheduledFuture> scheduledFutureMap = new ConcurrentHashMap<>();

    private final RestTemplate restTemplate = new RestTemplate();

    @Autowired
    IWishTypeService wishTypeService;
    @Autowired
    IWishLanguageService wishLanguageService;

    private static final Logger logger = LoggerFactory.getLogger(OrderConsumerImpl.class.getName());


    @Override
    public void startConsumer(String orderId) {
        OrderDetail ordersWishes = ordersWishesService.getOrderDetailById(orderId);
        Date startTime = ordersWishes.getStartTime();
        String startCron = convertToStartCron(startTime);
        String startKey = orderId + "start";
        String endKey = orderId + "stop";
        if (scheduledFutureMap.get(startKey) == null) {
            ScheduledFuture<?> startSchedule = threadPoolTaskScheduler.schedule(() -> {
                if (!laserControlServer.equals("null")) {
                    HashMap<String, String> param = new HashMap<>();
                    WishLanguage wishLanguage = wishLanguageService.getBaseMapper().selectById(ordersWishes.getLanguageId());
                    String proId = wishLanguage.getProId();
                    WishType wishType = wishTypeService.getBaseMapper().selectById(wishLanguage.getWishId());
                    param.put("pro_type", wishType.getWishType());
                    param.put("pro_id", proId);
                    param.put("sender", ordersWishes.getApptUser());
                    param.put("receiver", ordersWishes.getApptRecipient());
                    try {
                        String playUrl = laserControlServer + "/play";
                        restTemplate.postForObject(playUrl, param, String.class);
                        log.info(orderId + ":调用硬件接口成功，url: " + playUrl + "请求体" + param);
                        scheduledFutureMap.remove(startKey);
                    } catch (RestClientException e) {
                        log.info("调用硬件接口失败", e);
                    }
                }
            }, (triggerContext -> new CronTrigger(startCron).nextExecution(triggerContext)));
            scheduledFutureMap.put(startKey, startSchedule);
        }

        if (scheduledFutureMap.get(endKey) == null) {
            Date stopTime = ordersWishes.getStopTime();
            String stopCron = convertToStartCron(stopTime);
            ScheduledFuture<?> endSchedule = threadPoolTaskScheduler.schedule(() -> {
                log.info(orderId + ":执行订单消费结束流程，订单id：" + orderId);

                if (!laserControlServer.equals("null")) {
                    try {
                        String stopUrl = laserControlServer + "/stop";
                        restTemplate.getForObject(stopUrl, String.class);
                        log.info("调用硬件接口成功，url: " + stopUrl);
                        scheduledFutureMap.remove(endKey);
                    } catch (RestClientException e) {
                        log.info("调用硬件接口失败", e);
                    }
                }

                log.info("执行订单消费结束流程完毕，订单id：" + orderId);
            }, (triggerContext -> new CronTrigger(stopCron).nextExecution(triggerContext)));
            scheduledFutureMap.put(endKey, endSchedule);
        }

    }

    @Override
    public void cancelConsumer(String orderId) {
        String startKey = orderId + "start";
        String endKey = orderId + "stop";
        ScheduledFuture start = scheduledFutureMap.get(startKey);
        ScheduledFuture end = scheduledFutureMap.get(endKey);
        start.cancel(false);
        end.cancel(false);
    }

    public static String convertToStartCron(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        SimpleDateFormat sdf = new SimpleDateFormat("ss mm HH dd MM *");

        return sdf.format(calendar.getTime());
    }

    public static String convertToEndCron(Date date, Integer duration) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.SECOND, duration * 60 - 10);
        SimpleDateFormat sdf = new SimpleDateFormat("ss mm HH dd MM *");
        return sdf.format(calendar.getTime());
    }


}
